package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.itheima.reggie.common.Result;
import com.itheima.reggie.common.exception.BusinessException;
import com.itheima.reggie.common.exception.SystemException;
import com.itheima.reggie.common.utils.SMSUtils;
import com.itheima.reggie.common.utils.ValidateCodeUtils;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

/**
 * @author Yan
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/sendMsg")
    public Result<String> sendMsg(@RequestBody User user, HttpSession session){
        //发送短信验证码，使用阿里云短信服务（1.引入阿里依赖 2.使用工具类）

        String phone = user.getPhone();
        Integer code = ValidateCodeUtils.generateValidateCode(6);


        //把验证码存入Session中
        session.setAttribute("code",code.toString());
        //SMSUtils.sendMessage(phone,code.toString());
        log.info("验证码是............................{}",code);

        return Result.success("发送验证码成功");
    }

    /**
     * 接收前端json传递数据的两种方式：
     * 1.创建一个对象 接收json
     * 2.使用map集合接收（key-value）
     */
    @PostMapping("login")
    public Result<User> login(@RequestBody Map map,HttpSession session){
        //前端传递的用户输入的验证码
        String code = (String) map.get("code");
        //从session中获取验证码
        String codeInSession = (String) session.getAttribute("code");

        if (code.equals(codeInSession)){
            Result<User> login = userService.login(map);
            if (ObjectUtils.isNotEmpty(login)){
                User data = login.getData();
                Long id = data.getId();
                //在session中存入userId，同时覆盖验证码，使验证码只能使用一次
                session.setAttribute("user",id);
                //移除验证码
                session.removeAttribute("code");
                return login;
            }
        }
        return Result.error("登录失败");

    }

    @PostMapping("loginout")
    public Result<String> loginOut(HttpServletRequest request){
        request.getSession().removeAttribute("user");
        return Result.success("退出成功");
    }

}